《Shell学习笔记》环境变量

  1. export、unset的生效范围
    1. 脚本样例
    2. 执行结果
  2. 参考

export、unset的生效范围

一个子进程的环境变量决定于两个方面:

  1. 父进程在启动子进程那一刻,父进程的环境变量的快照作为基础。
  2. 父进程在启动子进程时注入的环境变量(e.g., NAN=5 ./env_test.sh)。

export、unset等操作仅对当前进程生效,也仅对命令执行后启动的子进程生效,而在之前启动的进程则无法生效。

脚本样例

#!/bin/bash

sub_proc() {
    while true; do
        sleep 1
        echo "[sub process $1] exec\"env | grep NAN\" get $(env | grep NAN)"
    done
}

graceful_exit() {
    echo "start graceful exit"

    if [ $sub_proc_a_pid ]; then
        echo "killing sub_proc_a_pid=$sub_proc_a_pid"
        kill -SIGTERM $sub_proc_a_pid
    fi
    if [ $sub_proc_b_pid ]; then
        echo "killing sub_proc_b_pid=$sub_proc_b_pid"
        kill -SIGTERM $sub_proc_b_pid
    fi

    echo "exiting..."
    exit 0
}

trap graceful_exit SIGTERM
trap graceful_exit SIGINT

sub_proc a &
sub_proc_a_pid=$!

count=0

while (($count < 10)); do
    count=$(expr $count + 1)
    echo "[main process] is waiting" "$count"

    if [ $count == 5 ]; then
        echo "[main process] exec\"export NAN=1\""
        export NAN=1
        echo "[main process] exec\"env | grep NAN\""
        env | grep NAN

        sub_proc b &
        sub_proc_b_pid=$!
    fi

    sleep 1
done

graceful_exit

执行结果

root@DESKTOP-6MVDBD1:~/samples-of-shell-scripts# NAN=5 ./env_test.sh
[main process] is waiting 1
[main process] is waiting 2
[sub process a] exec"env | grep NAN" get NAN=5
[main process] is waiting 3
[sub process a] exec"env | grep NAN" get NAN=5
[main process] is waiting 4
[sub process a] exec"env | grep NAN" get NAN=5
[main process] is waiting 5
[main process] exec"export NAN=1"
[main process] exec"env | grep NAN"
NAN=1
[sub process a] exec"env | grep NAN" get NAN=5
[main process] is waiting 6
[sub process b] exec"env | grep NAN" get NAN=1
[sub process a] exec"env | grep NAN" get NAN=5
[main process] is waiting 7
[sub process b] exec"env | grep NAN" get NAN=1
[sub process a] exec"env | grep NAN" get NAN=5
[main process] is waiting 8
[sub process a] exec"env | grep NAN" get NAN=5
[sub process b] exec"env | grep NAN" get NAN=1
[main process] is waiting 9
[sub process a] exec"env | grep NAN" get NAN=5
[sub process b] exec"env | grep NAN" get NAN=1
[main process] is waiting 10
[sub process b] exec"env | grep NAN" get NAN=1
[sub process a] exec"env | grep NAN" get NAN=5
start graceful exit
killing sub_proc_a_pid=43829
killing sub_proc_b_pid=43866
exiting...

参考


转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 nz_nuaa@163.com
github